package com.banyuan.课堂练习.Thread;

import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class Demo2Factory {
    private int n;
    private ArrayList<Callable<Integer>> list = new ArrayList<>();
    private ArrayList<FutureTask<Integer>> list2 = new ArrayList<>();
    private ArrayList<Thread> list3 = new ArrayList<>();
    private int start;
    private int end;
    private int avg;

    public Demo2Factory(int n, int start, int end) {
        this.n = n;
        this.start = Math.min(start, end);
        this.end = Math.max(start, end);
        avg = (end - start + 1) / n;
    }

    public ArrayList<Callable<Integer>> method() {
        for (int i = 0; i < n; i++) {
            if (i < n - 1) {
                Callable<Integer> d = new Demo2(start + avg * i, start + avg * i + avg - 1);
                list.add(d);
            } else {
                Callable<Integer> d = new Demo2(start + avg * i, end);
                list.add(d);
            }
        }
        return list;
    }

    public ArrayList<FutureTask<Integer>> method2() {
        method();
        for (int i = 0; i < n; i++) {
            list2.add(new FutureTask<Integer>(list.get(i)));
        }
        return list2;
    }

    public ArrayList<Thread> method3() {
        method2();
        for (int i = 0; i < n; i++) {
            list3.add(new Thread(list2.get(i)));
        }
        return list3;
    }

    public int getSum() throws ExecutionException, InterruptedException {
        method3();
        int sum = 0;
        for (int i = 0; i < n; i++) {
            list3.get(i).start();
        }

        for (int i = 0; i < n; i++) {
            System.out.println(list2.get(i).get());
            sum += list2.get(i).get();
        }

        return sum;
    }
}
